<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Logistics\Controllers;

use App\Eloquent\Ygt\Company;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\CustomerOrderPrice;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Logistics;
use App\Eloquent\Ygt\LogisticsNotes;
use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\UserMessage;
use App\Eloquent\Ygt\Warehouse;
use App\Eloquent\Ygt\WarehouseSendRelation;
use Framework\BaseClass\Api\Controller;
use App\Engine\Func;

class NotesController extends Controller
{
    public function index(){}
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',25);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $logisticsId        = request('id',0);
        if( !$userInfo || !$logisticsId ){
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;

        $where              = ['id'=>$logisticsId];
        $logistics          = Logistics::getInfo($where);
        $logisticsName      = $logistics->title ? $logistics->title : '未知快递';
        $where              = ['company_id'=>$companyId,'logistics_id'=>$logisticsId];
        $collection         = LogisticsNotes::getList($where);
        $notesList          = $collection->toArray();
        foreach($notesList as $key=>$val)
        {
            $order          = LogisticsNotes::getCustomerOrder($val['customer_order_id'],1);
            $notesList[$key]['order']           = $order;
            $notesList[$key]['status_name']   = '发货中';
            $notesList[$key]['logistics_name']   = $logisticsName;
        }
        return $notesList;
    }
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',1);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['id'=>$companyId];
        $company            = Company::getInfo($where);
        if(!$company)
        {
            xThrow( ERR_UNKNOWN,'厂信息出错' );
        }
        $isSubmit           = request('is_submit',0);
        $orderId            = request('id',0);
        $type               = request('type',1);//1从工作页面进入,2从订单页面进入
        if($isSubmit){
            $data                   = request()->all();
            $data['company_id']   = $companyId;
            $fieldList              = LogisticsNotes::$tableFieldList;
            $tableData              = LogisticsNotes::setDataByTableField($data,$fieldList);
            $tableDataCheckResult   = LogisticsNotes::checkDataByTableField($tableData,$fieldList);
            if($tableDataCheckResult !== true)
            {
                xThrow(ERR_PARAMETER, $tableDataCheckResult);
            }

            $editResult             = LogisticsNotes::edit($tableData,'id');
            if($editResult===false)
            {
                xThrow(ERR_UNKNOWN);
            }
            $logisticsNotesId       = $editResult;
            $logisticsSn            = $tableData['logistics_sn'];
            //这是在瞎搞
            $warehouseSendId        = isset($data['warehouse_send_id']) ? intval($data['warehouse_send_id']) : 0;

            $sellerUserId = 0;//对应的销售员ID
            if($warehouseSendId)
            {
                //跟发货单相关联的出库单
                $where              = ['warehouse_send_id'=>$warehouseSendId];
                $relationList       = WarehouseSendRelation::getList($where)->toArray();
                $warehouseIdArr     = $relationNumberArr = [];
                foreach($relationList as $key=>$val)
                {
                    $warehouseIdArr[]       = $val['warehouse_id'];
                    $relationNumberArr[$val['order_id']]    = $val['number'];
                }
                if(!empty($warehouseIdArr))
                {
                    //发货单中相关联的成品
                    $where                  = ['id'=>['in',$warehouseIdArr]];
                    $warehouseList          = Warehouse::getList($where)->toArray();
                    foreach($warehouseList as $key=>$val)
                    {
                        $valOrderId         = $val['order_id'];
                        $sendNumber         = $val['all_number'] - $val['now_number'];//已经发货的数量
                        $orderInfo          = Order::where('id',$valOrderId)->first();
                        if($orderInfo)
                        {
                            $orderNumber        = intval($orderInfo->product_num);
                            $customerOrderId    = intval($orderInfo->customer_order_id);
                            if($sendNumber < $orderNumber){
                                //订单数量尚未发完
                            }else{
                                //发完后订单状态改为已发货
                                $changeStatus       = 6;
                                \App\Engine\OrderEngine::changeCustomerOrderStatus($customerOrderId,$changeStatus);
                            }
                            //给相关人员发送消息
                            $foreignKey         = $customerOrderId;
                            $relationNumber     = isset($relationNumberArr[$valOrderId]) ? $relationNumberArr[$valOrderId] : 0;
                            if($relationNumber > 0)
                            {
                                //根据工单中客户id取客户对应的用户id
                                $customerId         = intval($orderInfo->customer_name);
                                $where              = ['id'=>$customerId];
                                $customer           = Customer::getInfo($where);
                                $customerName       = '';
                                $sellerUserId = $customer['add_user_id'];
                                if($customer)
                                {
                                    //给客户发消息
                                    $customerUsedrId    = $customer->user_id;
                                    $customerName       = $customer->customer_name;
                                    $saleArr            = config('ygt.sale_arr');
                                    $messageCompanyId   = $saleArr['company_id'];
                                    $companyName        = $company->title;
                                    $messageContent     = '工厂名称: '.$companyName;
                                    $messageContent     .= 'rnrn实际发货数量: '.$relationNumber;
                                    $messageContent     .= 'rnrn物流单号: '.$logisticsSn;
                                    $messageData        = [
                                        'company_id' => $messageCompanyId,
                                        'privilege_id' => 0,
                                        'form_user_id' => $userId,
                                        'to_user_id' => $customerUsedrId,
                                        'foreign_key' => $foreignKey,
                                        'type' => 21,
                                        'type_id' => $logisticsNotesId,
                                        'title' => '订单发货了',
                                        'content' => $messageContent,
                                        'type_status' => 1,
                                    ];
                                    //取消发消息
//                                    UserMessage::sendCustomerOrderMessage($messageData);
                                }
                                //根据工单中的订单id取下单人的用户id,和销售的用户id
                                //给下单人 和 销售员发消息
                                $priceColletion         = CustomerOrderPrice::where('customer_order_id',$customerOrderId)->first();
                                if($priceColletion && $customerName)
                                {
                                    $messageContent     = '客户名称: '.$customerName;
                                    $messageContent     .= 'rnrn实际发货数量: '.$relationNumber;
                                    $messageContent     .= 'rnrn物流单号: '.$logisticsSn;
                                    //下单人的用户id
                                    $singlepersonUid    = $priceColletion->singleperson_uid;
                                    //销售员的用户id
                                    $saleUid            = $priceColletion->sale_uid;
                                    $toUserIds          = $singlepersonUid.','.$saleUid;
                                    $messageData        = [
                                        'company_id' => $companyId,
                                        'privilege_id' => 0,
                                        'form_user_id' => $userId,
                                        'to_user_id' => $toUserIds,
                                        'foreign_key' => $foreignKey,
                                        'type' => 22,
                                        'type_id' => $logisticsNotesId,
                                        'title' => '订单发货了',
                                        'content' => $messageContent,
                                        'type_status' => 1,
                                    ];
                                    //取消发消息
//                                    UserMessage::sendCustomerOrderMessage($messageData);
                                }
                            }
                        }
                    }
                }
            }

            //给对应的销售员[和财务]发送消息，确认发货
            if($sellerUserId){
                if($foreignKey){
                    $customerOrderRow = \App\Eloquent\Ygt\Customer::where(['id'=>$foreignKey])->first();
                    $messageContent = "{$customerOrderRow['order_title']}已发货";

                    $messageData        = [
                        'company_id' => $companyId,
                        'privilege_id' => 0,
                        'form_user_id' => $userId,
                        'to_user_id' => $sellerUserId,
                        'foreign_key' => $foreignKey,
                        'type' => 43,//发货单详情
                        'type_id' => $warehouseSendId,
                        'title' => '发货员已发货',
                        'content' => $messageContent,
                        'type_status' => 1,
                        'theme'=>'发货消息'
                    ];
                    UserMessage::sendCustomerOrderMessage($messageData);

                    //给财务发送消息
                    $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
                    foreach ($privilegeIdList as $privilegeId) {
                        if ($privilegeId) {
                            $messageData        = [
                                'company_id' => $companyId,
                                'privilege_id' => $privilegeId,
                                'form_user_id' => $userId,
                                'to_user_id' => '',
                                'foreign_key' => $foreignKey,
                                'type' => 43,//发货单详情
                                'type_id' => $warehouseSendId,
                                'title' => '发货员已发货',
                                'content' => $messageContent,
                                'type_status' => 1,
                                'theme'=>'发货消息'
                            ];
                            UserMessage::sendCustomerOrderMessage($messageData);
                        }
                    }

                }
            }

            $result         = ['message'=>'编辑成功'];
            return $result;
        } else {
            $address                = [];
            switch ($type)
            {
                case 1:
                    //1从工作页面进入
                    break;
                case 2:
                    //2从订单页面进入
                    $address            = [
                        'phone'=>'','consignee'=>'','province_id'=>'','city_id'=>'',
                        'area_id'=>'','province_name'=>'','city_name'=>'','area_name'=>'',
                        'address'=>''
                    ];
                    break;
                default:
                    xThrow(ERR_UNKNOWN);
            }
            $result             = ['address'=>$address];
            return $result;
        }
    }
    public function detail()
    {
        $id             = request('id',0);
        $where          = ['id'=>$id];
        $info           = LogisticsNotes::getInfoData($where);
        if($info){
            //相关订单
            $orderList          = LogisticsNotes::getCustomerOrder($info['customer_order_id'],2);
            $result             = ['info'=>$info,'order_list'=>$orderList];
            return $result;
        }else{
            xThrow(ERR_UNKNOWN);
        }
    }
    public function del()
    {
        $userId             = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $id                 = request('id',0);
        if( !$userInfo || !$id ){
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['company_id'=>$companyId,'id'=>$id];
        $data               = ['status'=>2];
        $result             = LogisticsNotes::updateOneData($where,$data);
        if($result){
            return ['删除成功'];
        }else{
            xThrow(ERR_UNKNOWN);
        }
    }
}